/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO;

import java.util.List;
import javabeans.Event;
import javabeans.Plan;
import org.hibernate.HibernateException;
import org.hibernate.Query;

/**
 *
 * @author liweijiao
 */
public class IPlanDaoImpl extends DAO implements IPlanDao {

    public Plan newPlan(Plan plan) {
        try {
            begin();
            getSession().save(plan);
            commit();
            return plan;
        } catch (HibernateException e) {
            rollback();
            return null;

        }

    }

    public boolean deletePlan(int planid) {
        try {
            begin();
            getSession().delete(this.getPlan(planid));
            commit();
            return true;
        } catch (HibernateException e) {
            rollback();
            return false;

        }
    }

    public boolean updatePlan(Plan plan) {
        try {
            begin();
            getSession().saveOrUpdate(plan);
            commit();
            return true;
        } catch (HibernateException e) {
            rollback();
            return false;

        }
    }

    public Plan getPlan(int planid) {
        try {


            Query q = getSession().createQuery("from Plan p where p.planid = :pid");
            q.setInteger("pid", planid);
            Plan plan = (Plan) q.uniqueResult();
            IEventDaoImpl eventDao = new IEventDaoImpl();
            plan.setEvents(eventDao.getEventList(planid));
            return plan;
        } catch (HibernateException e) {
            e.printStackTrace();
            return null;

        }
    }

    public List<Plan> getPlanbyUserId(int userid) {
        try {

            begin();
            Query q = getSession().createQuery("from Plan p where p.member = :uid");
            q.setInteger("uid", userid);
            commit();
            List resultlist=q.list();
            List<Plan> list=(List<Plan>) resultlist;
           // if(list!=null)
           // System.out.println("list is not null");
            return list;


        } catch (HibernateException e) {
            rollback();
            return null;

        }
    }
}
